# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import base64
from sqlalchemy.schema import CreateSchema
from Environment import *
import Environment
import datetime
from web_lib.page import Page
from web_lib.webutils import Response, expose , json  ,change_schema
from dao.Ente import Ente
from dao.Servizio import Servizio
from dao.TipoEnte import TipoEnte
from dao.EnteServizio import EnteServizio
from lib.utils import mN, prep2json
from random import randint as rint

@expose('/pg/as_Ente/<action>')
@expose('/pg/as_Ente/')
@expose('/pg/as_Ente')
def anagraficaEnte(req, action=None):
    """
  id serial NOT NULL,
  denominazione_breve character varying(10) NOT NULL,
  denominazione character varying(100) NOT NULL,
  percentuale numeric(8,4) NOT NULL,
  percentuale_detrazione numeric(8,4),
  descrizione_detrazione character varying(100),
  id_tipo integer NOT NULL,
    """
    def randomCode():
        string = ""
        values = "23456789abcdefghmnpqrstuvzy"
        for a in range(12):
            b =  rint(0,26)
            string += values[b]
        return string


    def __show__(req, action=None):
        pageData = {'file' : "/pg/as_Ente",
                "dao":"AliquotaIva",
                "_dao_":"aliquota_iva",
                }
        return Page(req).render(pageData)

    def __list__(req, action=None):
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_denominazione =  req.form.get("fk_denominazione")
        daos = Ente().select(denominazione=fk_denominazione,
                            batchSize=batchSize,
                            offset=offset,
                            orderBy=sorting)
        count = Ente().count(denominazione=fk_denominazione,
                                    batchSize=None)
        item = {
            "Result":"OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)
            }
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __edit__(req, action=None):
        id = req.form.get("id")
        if id:
            d = Ente().getRecord(id=int(id))
        else:
            d = Ente()

        pageData = {'file': "pg/addedit/ae_ente",
                    "dao": d,
                    #"tipigeo":TipoGeo().select(batchSize=None),
                    "tipiente": TipoEnte().select(batchSize=None),
                    #"licenze": Licenza().select(batchSize=None),
                    #"catetags":','.join([x.tag_name for x in CategoriaTag().select(id_categoria=d.id, batchSize=None)]),
                    #"tags":Tag().select(batchSize=None)
                    }
        return Page(req).render(pageData)

    def __create__update__(req, action=None):
        """Aggiunge una riga alle pesate"""
        id = req.form.get("id")
        if id != "None":
            d = Ente().getRecord(id=int(id))
        else:
            d = Ente()
            d.codice = randomCode()
            d.data_registrazione = datetime.datetime.now()
            d.denominazione_breve = str(req.form.get("denominazione_breve"))
        d.denominazione = str(req.form.get("denominazione"))
        d.lati = str(req.form.get("lati"))
        d.longi = str(req.form.get("longi"))
        d.active = bool(req.form.get("active"))
        d.id_tipo = int(req.form.get("id_tipo"))
        if "icona_ente" in req.files:
            f = req.files["icona_ente"]
            data = f.read()
            if data:
                d.icona_ente = base64.b64encode(data)
        else:
            d.icona_ente = ""
        if "immagine" in req.files:
            f = req.files["immagine"]
            data = f.read()
            if data:
                d.immagine = base64.b64encode(data)
        else:
            d.immagine = ""
        try:
            d.persist()
            if id and id !="None":
                item = {"Result":"OK"}
            else:
                try:
                    engine.execute(CreateSchema(d.denominazione_breve.lower().replace(" ","")))
                except:
                    print "CREAZIONE SCHEMA {0} NON RIUSCITO O GIA ESISTENTE".format(d.denominazione_breve.lower().replace(" ",""))
                item = {"Result":"OK","Record":d.jsanity()}
                url_red = "/pg/as_Ente/"
                return Page(req).redirect(url_red)
        except:
            item = {
                "Result":"ERROR",
                "Message": "Creazione o modifica nuova riga non riuscita"}
        url_red = "/pg/as_Ente/"
        return Page(req).redirect(url_red)
        #jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        #return Response(jasoned)

    def __delete__(req, action=None):
        """Cancella una riga"""
        id = int(req.form.get("id"))
        d = Ente().getRecord(id=id)
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __preview__(req, action=None):
        from dao.EnteCategoria import EnteCategoria
        from dao.EnteServizio import EnteServizio
        from dao.CategoriaCampo import CategoriaCampo
        id = req.form.get("id")
        #if id != "None":
        #salvaInSessione(req, chiave="id_fornitore_selezionato", valore=id)
        comu = []
        ente = Ente().getRecord(id=id)
        gendict= {}
        #cataloghi = [m.categoria.tipo_categoria for m in ente.entecategoria]
        cataloghi = [m.categoria.tipo_categoria for m in EnteCategoria().select(id_ente=ente.id)]
        cats = list(set(cataloghi))
        cata = []
        catadict = {}
        for ca in cats:
            categorie = []
            categoriedict = {}
            pp = 0
            for c in EnteCategoria().select(id_ente=ente.id):
                if c.categoria.tipo_categoria == ca:
                    pp = pp + 1
                    categorie.append(c.categoria)
                    campo = []
                    campodict = {}
                    for d in CategoriaCampo().select(id_categoria=c.categoria.id):
                    #for d in c.categoria.categoriacampo:
                        campo.append(d.campo)
                    #campodict["ncampi"] = len(c.categoria.categoriacampo)
                    campodict["campi"] = campo
                    categorie.append (campodict)
                categoriedict["categoria"] = categorie
            catadict[ca] = categoriedict
        cata.append(catadict)
        gendict["cataloghi"] = cata
        comu.append(gendict)
        #comu.append(cats)
        diz = {"ente":comu}
        print "DIZ", diz
        pageData = {'file': "/pg/ente",
                    "dao": ente,
                    "diz":diz,
                    }
        return Page(req).render(pageData)

    def __json__(req, action=None):
        codice = req.args.get("codice")
        comu = []
        if not codice:
            return Response("{}")
        ente = Ente().select(codice=codice)
        if ente:
            ente = ente[0]
            Environment.census = True
            Environment.sch = ente.denominazione_breve.lower().replace(" ", "")
            change_schema(req, ente.denominazione_breve.lower().replace(" ", ""))
            item = prep2json(ente),
            comu.append(item)
            servizi = EnteServizio().select(id_ente=ente.id, batchSize=None)
            serv = [a.servizio for a in servizi]
            comu.append({"servizi":serv})
            jasoned = json.dumps(comu,sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False, encoding='utf8')
            return Response(jasoned)
        else:
            return Response("{}")

    def __jsons__(req, action=None):
        passwd = req.args.get("passwd")
        if passwd != "aabb3355gh22":
            return Response("")
        else:
            comu = []
            enti = Ente().select()
            for ente in enti:
                Environment.census = True
                item = prep2json(ente),
                servizi = EnteServizio().select(id_ente=ente.id, batchSize=None)
                serv = [a.servizio for a in servizi]
                comu.append([ente.denominazione,item,{"servizi":serv}])
            jasoned = json.dumps(comu,sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False, encoding='utf8')
            return Response(jasoned)


    def __get_tai__(req, action=None):
        tai = TipoEnte().select(batchSize = None)
        item = {"Result":"OK",
                    "Options":[{"DisplayText":"","Value":""}]+ [{
                        "DisplayText":str(d.denominazione),
                        "Value":d.id} for d in tai]}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __get_ente__(req, action=None):
        tai = Ente().select(batchSize = None)
        #item = {"Result":"OK",
                    #"Options":[{"DisplayText":"","Value":""}]+ [{
                        #"DisplayText":str(d.denominazione),
                        #"Value":d.id} for d in tai]}
        item = [{"id":d.id,"denominazione":str(d.denominazione)} for d in tai]
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)


    def __get_enti__(req, action=None):
        fk = req.args.get("query")
        servizio = req.args.get("servizio")
        serv = Servizio().select(denominazione = servizio)
        if serv:
            id_serv = serv[0].id
        print "FKKKKKKKKKKKKKK", fk  , req.args.to_dict(),  req.form.to_dict()
        daos = Ente().select(denominazione=fk, batchSize = 40)
        ids_ent_serv = [d.id_ente for d in EnteServizio().select(id_servizio = id_serv, batchSize=None)]
        daoss = []
        for d in daos:
            if d.id in ids_ent_serv:
                daoss.append(d)

        item ={"query": "Unit","suggestions": [
                {"value":str(d.denominazione),
                "id_ente":d.id,
                } for d in daoss]
                }

        #jasoned = json.dumps(prep2json(item))
        jasoned = json.dumps(item)
        return Response(jasoned)




    if action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    elif action == "Edit":
        return __edit__(req, action=action)
    elif action == "GetTipoEnte":
        return __get_tai__(req, action=action)
    elif action == "GetEnte":
        return __get_ente__(req, action=action)
    elif action == "GetEnti":
        return __get_enti__(req, action=action)
    elif action == "Preview":
        return __preview__(req, action=action)
    elif action == "Daojson":
        return __json__(req, action=action)
    elif action == "Daojsons":
        return __jsons__(req, action=action)
    else:
        return __show__(req, action=action)
